<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员面板 - 本地有约</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #8aa899;
            --primary-dark: #6a8a7a;
            --primary-light: #a8c0b0;
            --secondary-color: #f5f5f5;
            --text-color: #333;
            --text-light: #666;
            --border-color: #ddd;
            --admin-color: #dc3545;
            --admin-light: #f8d7da;
            --warning-color: #ffc107;
            --success-color: #28a745;
        }

        .admin-header {
            background: linear-gradient(135deg, var(--admin-color), #c82333);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }

        .stat-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card .card-body {
            padding: 2rem;
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }

        .stat-icon {
            font-size: 3rem;
            opacity: 0.7;
        }

        .recent-item {
            border: none;
            border-left: 4px solid var(--primary-color);
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }

        .recent-item:hover {
            border-left-color: var(--admin-color);
            background-color: var(--secondary-color);
        }

        .admin-sidebar {
            background: linear-gradient(180deg, #2c3e50, #34495e);
            color: white;
            min-height: 100vh;
            padding: 0;
        }

        .admin-sidebar .nav-link {
            color: #ecf0f1;
            padding: 1rem 1.5rem;
            border-left: 4px solid transparent;
            transition: all 0.3s ease;
        }

        .admin-sidebar .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.1);
            border-left-color: var(--admin-color);
            color: white;
        }

        .admin-sidebar .nav-link.active {
            background-color: rgba(220, 53, 69, 0.2);
            border-left-color: var(--admin-color);
            color: white;
        }

        .admin-content {
            padding: 2rem;
        }

        .badge-admin {
            background-color: var(--admin-color);
        }

        .badge-pending {
            background-color: var(--warning-color);
            color: #000;
        }

        .badge-approved {
            background-color: var(--success-color);
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }

        .table th {
            border-top: none;
            font-weight: 600;
        }

        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        /* 仪表板网格样式 */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .dashboard-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            transition: transform 0.3s ease;
        }

        .dashboard-card:hover {
            transform: translateY(-5px);
        }

        .card-title {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 1rem;
            color: var(--text-color);
        }

        .quick-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }

        .stat-item {
            text-align: center;
            padding: 1rem;
            background: var(--secondary-color);
            border-radius: 10px;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }

        .stat-label {
            font-size: 0.875rem;
            color: var(--text-light);
        }

        .recent-activity {
            max-height: 400px;
            overflow-y: auto;
        }

        .activity-item {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            border-bottom: 1px solid var(--border-color);
        }

        .activity-item:last-child {
            border-bottom: none;
        }

        .activity-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            background: var(--primary-light);
            color: var(--primary-color);
        }

        .activity-content {
            flex: 1;
        }

        .activity-title {
            font-weight: 600;
            margin-bottom: 0.25rem;
        }

        .activity-time {
            font-size: 0.875rem;
            color: var(--text-light);
        }

        /* 活动详情模态框样式 */
        .event-detail-item {
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
        }

        .event-detail-label {
            font-weight: 600;
            min-width: 100px;
            margin-right: 1rem;
            color: var(--text-light);
        }

        .event-detail-item:last-child {
            border-bottom: none;
        }

        .event-modal .modal-header {
            background: linear-gradient(135deg, var(--admin-color), #c82333);
            color: white;
        }

        .event-modal .modal-body {
            max-height: 60vh;
            overflow-y: auto;
        }

        /* 积分调整卡片样式 */
        .adjust-points-card {
            display: none;
            position: sticky;
            top: 20px;
            z-index: 100;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 2px solid var(--primary-color);
        }

        .adjust-points-card h5 {
            color: var(--admin-color);
            margin-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 0.5rem;
        }

        .adjust-points-card .form-group {
            margin-bottom: 1rem;
        }

        .adjust-points-card .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .adjust-points-card .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 1rem;
        }

        .adjust-points-card .btn-group .btn {
            flex: 1;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 admin-sidebar">
                <div class="d-flex flex-column align-items-center py-4">
                    <img src="{% if user.avatar and user.avatar.url %}{{ user.avatar.url }}{% else %}https://via.placeholder.com/80{% endif %}"
                         alt="管理员头像" class="rounded-circle mb-3" width="80" height="80" style="object-fit: cover;">
                    <h5 class="mb-1">{{ user.username }}</h5>
                    <span class="badge badge-admin">超级管理员</span>
                </div>

                <nav class="nav flex-column">
                    <a class="nav-link active" href="javascript:void(0)" onclick="showView('dashboard')">
                        <i class="fas fa-tachometer-alt me-2"></i>仪表板
                    </a>
                    <a class="nav-link" href="javascript:void(0)" onclick="showView('users')">
                        <i class="fas fa-users me-2"></i>用户管理
                    </a>
                    <a class="nav-link" href="javascript:void(0)" onclick="showView('events')">
                        <i class="fas fa-calendar-alt me-2"></i>活动管理
                    </a>
                    <a class="nav-link" href="javascript:void(0)" onclick="showView('approval')">
                        <i class="fas fa-check-circle me-2"></i>活动审核
                    </a>
                    <a class="nav-link" href="javascript:void(0)" onclick="showView('points')">
                        <i class="fas fa-coins me-2"></i>积分管理
                    </a>
                    <a class="nav-link" href="javascript:void(0)" onclick="showView('statistics')">
                        <i class="fas fa-chart-bar me-2"></i>数据统计
                    </a>
                    <a class="nav-link" href="javascript:void(0)" onclick="showView('settings')">
                        <i class="fas fa-cog me-2"></i>系统设置
                    </a>
                    <a class="nav-link" href="{% url 'location:index' %}">
                        <i class="fas fa-home me-2"></i>返回首页
                    </a>
                    <a class="nav-link" href="{% url 'customer:logout' %}">
                        <i class="fas fa-sign-out-alt me-2"></i>退出登录
                    </a>
                </nav>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9 col-lg-10 admin-content">
                <!-- 页面头部 -->
{#                <div class="admin-header rounded">#}
{#                    <div class="row align-items-center">#}
{#                        <div class="col">#}
{#                            <h1 class="h3 mb-0">#}
{#                                <i class="fas fa-crown me-2"></i>管理员面板#}
{#                            </h1>#}
{#                            <p class="mb-0 opacity-75">管理系统数据和用户信息</p>#}
{#                        </div>#}
{#                        <div class="col-auto">#}
{#                            <span class="badge bg-light text-dark">#}
{#                                <i class="fas fa-clock me-1"></i>#}
{#                                {% now "Y-m-d H:i" %}#}
{#                            </span>#}
{#                        </div>#}
{#                    </div>#}
{#                </div>#}

                <!-- 仪表板视图 -->
                <div id="dashboard-view" class="content-view">
                    <!-- 统计卡片 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-primary">{{ total_users }}</div>
                                    <div class="stat-icon text-primary">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <h5 class="card-title">总用户数</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-success">{{ total_events }}</div>
                                    <div class="stat-icon text-success">
                                        <i class="fas fa-calendar-check"></i>
                                    </div>
                                    <h5 class="card-title">活动总数</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-info" id="total-points">0</div>
                                    <div class="stat-icon text-info">
                                        <i class="fas fa-coins"></i>
                                    </div>
                                    <h5 class="card-title">系统总积分</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-warning">{{ pending_events_count }}</div>
                                    <div class="stat-icon text-warning">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <h5 class="card-title">待审核活动</h5>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 仪表板网格布局 -->
                    <div class="dashboard-grid">
                        <!-- 快速统计 -->
                        <div class="dashboard-card">
                            <h5 class="card-title">
                                <i class="fas fa-chart-line me-2 text-primary"></i>快速统计
                            </h5>
                            <div class="quick-stats">
                                <div class="stat-item">
                                    <div class="stat-value" id="today-users">0</div>
                                    <div class="stat-label">今日新增用户</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value" id="today-events">0</div>
                                    <div class="stat-label">今日新增活动</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value" id="active-users">0</div>
                                    <div class="stat-label">活跃用户</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value" id="total-rewards">0</div>
                                    <div class="stat-label">商品总数</div>
                                </div>
                            </div>
                        </div>

                        <!-- 最近活动 -->
                        <div class="dashboard-card">
                            <h5 class="card-title">
                                <i class="fas fa-history me-2 text-success"></i>最近活动
                            </h5>
                            <div class="recent-activity" id="recent-activities">
                                <!-- 最近活动内容将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载最近活动...</p>
                                </div>
                            </div>
                        </div>

                        <!-- 系统状态 -->
                        <div class="dashboard-card">
                            <h5 class="card-title">
                                <i class="fas fa-server me-2 text-warning"></i>系统状态
                            </h5>
                            <div class="system-status">
                                <div class="status-item mb-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>用户服务</span>
                                        <span class="badge bg-success">正常</span>
                                    </div>
                                </div>
                                <div class="status-item mb-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>活动服务</span>
                                        <span class="badge bg-success">正常</span>
                                    </div>
                                </div>
                                <div class="status-item mb-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>积分服务</span>
                                        <span class="badge bg-success">正常</span>
                                    </div>
                                </div>
                                <div class="status-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>数据库</span>
                                        <span class="badge bg-success">正常</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 快速操作 -->
                        <div class="dashboard-card">
                            <h5 class="card-title">
                                <i class="fas fa-bolt me-2 text-danger"></i>快速操作
                            </h5>
                            <div class="quick-actions">
                                <button class="btn btn-outline-primary w-100 mb-2" onclick="showView('users')">
                                    <i class="fas fa-users me-2"></i>用户管理
                                </button>
                                <button class="btn btn-outline-success w-100 mb-2" onclick="showView('events')">
                                    <i class="fas fa-calendar-alt me-2"></i>活动管理
                                </button>
                                <button class="btn btn-outline-warning w-100 mb-2" onclick="showView('approval')">
                                    <i class="fas fa-check-circle me-2"></i>活动审核
                                </button>
                                <button class="btn btn-outline-info w-100" onclick="showView('points')">
                                    <i class="fas fa-coins me-2"></i>积分管理
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 最近用户注册 -->
                    <div class="card mb-4">
                        <div class="card-header bg-white">
                            <h5 class="mb-0">
                                <i class="fas fa-user-plus me-2 text-primary"></i>最近注册用户
                            </h5>
                        </div>
                        <div class="card-body">
                            <div id="recent-users">
                                <!-- 最近用户将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载用户数据...</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 最近活动创建 -->
                    <div class="card">
                        <div class="card-header bg-white">
                            <h5 class="mb-0">
                                <i class="fas fa-calendar-plus me-2 text-success"></i>最近创建活动
                            </h5>
                        </div>
                        <div class="card-body">
                            <div id="recent-events">
                                <!-- 最近活动将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-success" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载活动数据...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 用户管理视图 -->
                <div id="users-view" class="content-view" style="display: none;">
                    <div class="admin-header rounded">
                        <div class="row align-items-center">
                            <div class="col">
                                <h1 class="h3 mb-0">
                                    <i class="fas fa-users me-2"></i>用户管理
                                </h1>
                                <p class="mb-0 opacity-75">管理系统所有用户</p>
                            </div>
                            <div class="col-auto">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-users me-1"></i>
                                    {{ total_users }} 用户
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div id="users-list">
                                <!-- 用户列表将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载用户数据...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 活动管理视图 -->
                <div id="events-view" class="content-view" style="display: none;">
                    <div class="admin-header rounded">
                        <div class="row align-items-center">
                            <div class="col">
                                <h1 class="h3 mb-0">
                                    <i class="fas fa-calendar-alt me-2"></i>活动管理
                                </h1>
                                <p class="mb-0 opacity-75">管理系统所有活动</p>
                            </div>
                            <div class="col-auto">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-calendar me-1"></i>
                                    {{ total_events }} 活动
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div id="events-list">
                                <!-- 活动列表将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-success" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载活动数据...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 活动审核视图 -->
                <div id="approval-view" class="content-view" style="display: none;">
                    <div class="admin-header rounded">
                        <div class="row align-items-center">
                            <div class="col">
                                <h1 class="h3 mb-0">
                                    <i class="fas fa-check-circle me-2"></i>活动审核
                                </h1>
                                <p class="mb-0 opacity-75">审核待发布的活动</p>
                            </div>
                            <div class="col-auto">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-clock me-1"></i>
                                    <span id="pending-count">{{ pending_events_count }}</span> 待审核
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div id="pending-events-list">
                                <!-- 待审核活动列表将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-warning" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载待审核活动...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 积分管理视图 -->
                <div id="points-view" class="content-view" style="display: none;">
                    <div class="admin-header rounded">
                        <div class="row align-items-center">
                            <div class="col">
                                <h1 class="h3 mb-0">
                                    <i class="fas fa-coins me-2"></i>积分管理
                                </h1>
                                <p class="mb-0 opacity-75">管理系统积分和用户积分记录</p>
                            </div>
                            <div class="col-auto">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-coins me-1"></i>
                                    <span id="total-points-count">0</span> 总积分
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- 积分调整卡片 -->
                    <div class="adjust-points-card" id="adjustPointsCard">
                        <h5><i class="fas fa-edit me-2"></i>调整用户积分</h5>
                        <div class="form-group">
                            <label class="form-label">用户ID（多个用户用逗号分隔）</label>
                            <input type="text" class="form-control" id="adjust-user-ids" placeholder="例如: 1,2,3">
                        </div>
                        <div class="form-group">
                            <label class="form-label">积分调整数量</label>
                            <input type="number" class="form-control" id="adjust-points" placeholder="正数为增加，负数为减少">
                        </div>
                        <div class="form-group">
                            <label class="form-label">调整原因</label>
                            <input type="text" class="form-control" id="adjust-remark" placeholder="请输入调整原因" value="管理员调整">
                        </div>
                        <div class="btn-group">
                            <button class="btn btn-primary" onclick="submitAdjustPoints()">
                                <i class="fas fa-check me-1"></i>确认调整
                            </button>
                            <button class="btn btn-secondary" onclick="hideAdjustPointsCard()">
                                <i class="fas fa-times me-1"></i>取消
                            </button>
                        </div>
                    </div>

                    <!-- 积分统计卡片 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-primary" id="stats-total-issued">0</div>
                                    <div class="stat-icon text-primary">
                                        <i class="fas fa-arrow-up"></i>
                                    </div>
                                    <h5 class="card-title">总发放积分</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-success" id="stats-total-used">0</div>
                                    <div class="stat-icon text-success">
                                        <i class="fas fa-arrow-down"></i>
                                    </div>
                                    <h5 class="card-title">总使用积分</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-info" id="stats-total-transactions">0</div>
                                    <div class="stat-icon text-info">
                                        <i class="fas fa-exchange-alt"></i>
                                    </div>
                                    <h5 class="card-title">总交易数</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-warning" id="stats-unique-users">0</div>
                                    <div class="stat-icon text-warning">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <h5 class="card-title">涉及用户</h5>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 筛选和操作区域 -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-2">
                                    <input type="text" class="form-control" id="search-username" placeholder="用户名">
                                </div>
                                <div class="col-md-2">
                                    <input type="text" class="form-control" id="search-phone" placeholder="手机号">
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="search-transaction-type">
                                        <option value="">全部交易类型</option>
                                        <option value="earn">获得积分</option>
                                        <option value="spend">消费积分</option>
                                        <option value="refund">退还积分</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="search-source-type">
                                        <option value="">全部来源</option>
                                        <option value="event_create">创建活动</option>
                                        <option value="event_join">参加活动</option>
                                        <option value="event_review">活动评价</option>
                                        <option value="post_create">发布帖子</option>
                                        <option value="comment_create">发表评论</option>
                                        <option value="daily_login">每日登录</option>
                                        <option value="profile_complete">完善资料</option>
                                        <option value="reward_redemption">积分兑换</option>
                                        <option value="system_bonus">系统奖励</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input type="date" class="form-control" id="search-start-time">
                                </div>
                                <div class="col-md-2">
                                    <input type="date" class="form-control" id="search-end-time">
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col">
                                    <button class="btn btn-primary" onclick="loadPointsData()">
                                        <i class="fas fa-search me-1"></i>搜索
                                    </button>
                                    <button class="btn btn-success" onclick="showAdjustPointsCard()">
                                        <i class="fas fa-edit me-1"></i>调整积分
                                    </button>
                                    <button class="btn btn-info" onclick="showPointsRules()">
                                        <i class="fas fa-cog me-1"></i>积分规则
                                    </button>
                                    <button class="btn btn-warning" onclick="exportPointsData()">
                                        <i class="fas fa-download me-1"></i>导出数据
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 积分记录列表 -->
                    <div class="card">
                        <div class="card-body">
                            <div id="points-list">
                                <!-- 积分记录将通过JavaScript动态加载 -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-info" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">加载积分数据...</p>
                                </div>
                            </div>
                            <!-- 分页控件 -->
                            <div class="d-flex justify-content-between align-items-center mt-3">
                                <div class="text-muted" id="points-pagination-info">
                                    显示 0 条记录，共 0 条
                                </div>
                                <nav>
                                    <ul class="pagination mb-0" id="points-pagination">
                                        <!-- 分页按钮将通过JavaScript动态生成 -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 数据统计视图 -->
                <div id="statistics-view" class="content-view" style="display: none;">
                    <div class="admin-header rounded">
                        <div class="row align-items-center">
                            <div class="col">
                                <h1 class="h3 mb-0">
                                    <i class="fas fa-chart-bar me-2"></i>数据统计
                                </h1>
                                <p class="mb-0 opacity-75">系统数据统计和分析</p>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-light" onclick="refreshStatistics()">
                                    <i class="fas fa-sync-alt me-1"></i>刷新数据
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 统计概览 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-primary" id="stats-total-users">0</div>
                                    <div class="stat-icon text-primary">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <h5 class="card-title">总用户数</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-success" id="stats-total-events">0</div>
                                    <div class="stat-icon text-success">
                                        <i class="fas fa-calendar-check"></i>
                                    </div>
                                    <h5 class="card-title">总活动数</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-info" id="stats-active-users">0</div>
                                    <div class="stat-icon text-info">
                                        <i class="fas fa-user-check"></i>
                                    </div>
                                    <h5 class="card-title">月活跃用户</h5>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <div class="stat-number text-warning" id="stats-total-points">0</div>
                                    <div class="stat-icon text-warning">
                                        <i class="fas fa-coins"></i>
                                    </div>
                                    <h5 class="card-title">系统总积分</h5>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 图表区域 -->
                    <div class="row mb-4">
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">用户注册趋势（最近30天）</h5>
                                </div>
                                <div class="card-body">
                                    <div id="registration-chart" style="height: 300px; position: relative;">
                                        <canvas id="registrationChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">活动创建趋势（最近30天）</h5>
                                </div>
                                <div class="card-body">
                                    <div id="events-chart" style="height: 300px; position: relative;">
                                        <canvas id="eventsChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 详细统计 -->
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">用户等级分布</h5>
                                </div>
                                <div class="card-body">
                                    <div id="level-chart" style="height: 300px; position: relative;">
                                        <canvas id="levelChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">热门活动分类</h5>
                                </div>
                                <div class="card-body">
                                    <div id="category-chart" style="height: 300px; position: relative;">
                                        <canvas id="categoryChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 系统设置视图 -->
                <div id="settings-view" class="content-view" style="display: none;">
                    <div class="admin-header rounded">
                        <div class="row align-items-center">
                            <div class="col">
                                <h1 class="h3 mb-0">
                                    <i class="fas fa-cog me-2"></i>系统设置
                                </h1>
                                <p class="mb-0 opacity-75">管理系统配置和设置</p>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-success" onclick="saveSystemSettings()">
                                    <i class="fas fa-save me-1"></i>保存设置
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <!-- 基本设置 -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>基本设置</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">网站名称</label>
                                            <input type="text" class="form-control" id="setting-site-name">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">管理员邮箱</label>
                                            <input type="email" class="form-control" id="setting-admin-email">
                                        </div>
                                        <div class="col-12">
                                            <label class="form-label">网站描述</label>
                                            <textarea class="form-control" id="setting-site-description" rows="3"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 功能设置 -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-toggle-on me-2"></i>功能设置</h5>
                                </div>
                                <div class="card-body">
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="setting-auto-approve">
                                        <label class="form-check-label" for="setting-auto-approve">自动审核活动</label>
                                    </div>
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="setting-points-enabled">
                                        <label class="form-check-label" for="setting-points-enabled">启用积分系统</label>
                                    </div>
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="setting-registration-open">
                                        <label class="form-check-label" for="setting-registration-open">开放用户注册</label>
                                    </div>
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="setting-maintenance-mode">
                                        <label class="form-check-label" for="setting-maintenance-mode">维护模式</label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <!-- 系统工具 -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-tools me-2"></i>系统工具</h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <button class="btn btn-outline-primary" onclick="clearSystemCache()">
                                            <i class="fas fa-broom me-2"></i>清除系统缓存
                                        </button>
                                        <button class="btn btn-outline-success" onclick="createSystemBackup()">
                                            <i class="fas fa-download me-2"></i>创建系统备份
                                        </button>
                                        <button class="btn btn-outline-info" onclick="updateSystemInfo()">
                                            <i class="fas fa-sync me-2"></i>更新系统信息
                                        </button>
                                        <button class="btn btn-outline-warning" onclick="checkSystemHealth()">
                                            <i class="fas fa-heartbeat me-2"></i>系统健康检查
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- 系统信息 -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-server me-2"></i>系统信息</h5>
                                </div>
                                <div class="card-body">
                                    <div class="system-info">
                                        <div class="info-item d-flex justify-content-between mb-2">
                                            <span>Django 版本</span>
                                            <span class="text-muted" id="info-django-version">加载中...</span>
                                        </div>
                                        <div class="info-item d-flex justify-content-between mb-2">
                                            <span>Python 版本</span>
                                            <span class="text-muted" id="info-python-version">加载中...</span>
                                        </div>
                                        <div class="info-item d-flex justify-content-between mb-2">
                                            <span>数据库</span>
                                            <span class="text-muted" id="info-database">加载中...</span>
                                        </div>
                                        <div class="info-item d-flex justify-content-between mb-2">
                                            <span>服务器时间</span>
                                            <span class="text-muted" id="info-server-time">加载中...</span>
                                        </div>
                                        <div class="info-item d-flex justify-content-between">
                                            <span>运行时间</span>
                                            <span class="text-muted" id="info-uptime">加载中...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 活动详情模态框 -->
                    <div class="modal fade event-modal" id="eventDetailsModal" tabindex="-1" aria-labelledby="eventDetailsModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="eventDetailsModalLabel">
                                        <i class="fas fa-calendar-alt me-2"></i>活动详情
                                    </h5>
                                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div id="eventDetailsContent">
                                        <!-- 活动详情内容将通过JavaScript动态加载 -->
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                </div>
                            </div>
                        </div>
                    </div>

    <!-- 积分规则管理模态框 -->
    <div class="modal fade" id="pointsRulesModal" tabindex="-1" aria-labelledby="pointsRulesModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="pointsRulesModalLabel">
                        <i class="fas fa-cog me-2"></i>积分规则管理
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="points-rules-content">
                        <!-- 积分规则内容将通过JavaScript动态加载 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // DOM切换功能
    let currentView = 'dashboard';

    function showView(viewName) {
        // 隐藏所有视图
        document.querySelectorAll('.content-view').forEach(view => {
            view.style.display = 'none';
        });

        // 移除所有侧边栏激活状态
        document.querySelectorAll('.admin-sidebar .nav-link').forEach(link => {
            link.classList.remove('active');
        });

        // 显示选中的视图
        document.getElementById(`${viewName}-view`).style.display = 'block';

        // 设置侧边栏激活状态
        document.querySelector(`[onclick="showView('${viewName}')"]`).classList.add('active');

        currentView = viewName;

        // 加载对应数据
        if (viewName === 'users') {
            loadUsersData();
        } else if (viewName === 'events') {
            loadEventsData();
        } else if (viewName === 'approval') {
            loadPendingEventsData();
        } else if (viewName === 'dashboard') {
            loadDashboardData();
        } else if (viewName === 'points') {
            loadPointsData();
        }else if (viewName === 'statistics') {
        loadStatisticsData();
        } else if (viewName === 'settings') {
            loadSystemSettings();
        }
    }

    // 获取CSRF令牌的函数
    function getCSRFToken() {
        const name = 'csrftoken';
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 显示消息提示
    function showMessage(message, type = 'success') {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;

        // 在页面顶部显示消息
        const messageContainer = document.createElement('div');
        messageContainer.innerHTML = alertHtml;
        document.querySelector('.admin-content').insertBefore(messageContainer, document.querySelector('.admin-content').firstChild);

        // 5秒后自动消失
        setTimeout(() => {
            if (messageContainer.firstChild) {
                messageContainer.firstChild.remove();
            }
        }, 5000);
    }

    // ============================
    // 仪表板功能
    // ============================

    // 加载仪表板数据
    function loadDashboardData() {
        fetch('/customer/admin/dashboard-stats/')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('total-points').textContent = data.total_points;
                    document.getElementById('today-users').textContent = data.today_users;
                    document.getElementById('today-events').textContent = data.today_events;
                    document.getElementById('active-users').textContent = data.active_users;
                    document.getElementById('total-rewards').textContent = data.total_rewards;

                    // 加载最近活动
                    loadRecentActivities(data.recent_activities);
                    // 加载最近用户
                    loadRecentUsers(data.recent_users);
                    // 加载最近活动
                    loadRecentEvents(data.recent_events);
                }
            })
            .catch(error => {
                console.error('Error loading dashboard stats:', error);
            });
    }

    // 加载最近活动
    function loadRecentActivities(activities) {
        const container = document.getElementById('recent-activities');
        container.innerHTML = '';

        if (activities && activities.length > 0) {
            activities.forEach(activity => {
                const activityHTML = `
                    <div class="activity-item">
                        <div class="activity-icon">
                            <i class="fas ${getActivityIcon(activity.type)}"></i>
                        </div>
                        <div class="activity-content">
                            <div class="activity-title">${activity.title}</div>
                            <div class="activity-time">${activity.time}</div>
                        </div>
                    </div>
                `;
                container.innerHTML += activityHTML;
            });
        } else {
            container.innerHTML = '<div class="text-center py-4 text-muted">暂无最近活动</div>';
        }
    }

    // 获取活动图标
    function getActivityIcon(type) {
        const icons = {
            'user_register': 'fa-user-plus',
            'event_create': 'fa-calendar-plus',
            'event_join': 'fa-user-check',
            'points_earn': 'fa-coins',
            'reward_redeem': 'fa-gift'
        };
        return icons[type] || 'fa-circle';
    }

    // 加载最近用户
    function loadRecentUsers(users) {
        const container = document.getElementById('recent-users');
        container.innerHTML = '';

        if (users && users.length > 0) {
            users.forEach(user => {
                const userHTML = `
                    <div class="card recent-item mb-2">
                        <div class="card-body py-2">
                            <div class="d-flex align-items-center">
                                <img src="${user.avatar_url}" alt="用户头像" class="rounded-circle me-3" width="40" height="40" style="object-fit: cover;">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">${user.username}</h6>
                                    <small class="text-muted">${user.email}</small>
                                </div>
                                <div class="text-end">
                                    <small class="text-muted">${user.join_time}</small>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                container.innerHTML += userHTML;
            });
        } else {
            container.innerHTML = '<div class="text-center py-4 text-muted">暂无最近注册用户</div>';
        }
    }

    // 加载最近活动
    function loadRecentEvents(events) {
        const container = document.getElementById('recent-events');
        container.innerHTML = '';

        if (events && events.length > 0) {
            events.forEach(event => {
                const eventHTML = `
                    <div class="card recent-item mb-2">
                        <div class="card-body py-2">
                            <h6 class="mb-2">${event.title}</h6>
                            <div class="d-flex justify-content-between text-muted small">
                                <span><i class="fas fa-user me-1"></i>${event.organizer}</span>
                                <span><i class="fas fa-calendar me-1"></i>${event.create_time}</span>
                            </div>
                        </div>
                    </div>
                `;
                container.innerHTML += eventHTML;
            });
        } else {
            container.innerHTML = '<div class="text-center py-4 text-muted">暂无最近创建活动</div>';
        }
    }

    // ============================
    // 用户管理功能
    // ============================

    // 加载用户数据
    function loadUsersData() {
        fetch('/customer/admin/users-data/')
            .then(response => response.json())
            .then(data => {
                const usersContainer = document.getElementById('users-list');
                usersContainer.innerHTML = '';

                if (data.users && data.users.length > 0) {
                    data.users.forEach(user => {
                        // 判断是否是当前登录的管理员自己
                        const isCurrentUser = user.id === {{ user.id }};

                        const userHTML = `
                            <div class="card recent-item">
                                <div class="card-body py-3">
                                    <div class="d-flex align-items-center">
                                        <img src="${user.avatar_url}" alt="用户头像" class="rounded-circle me-3" width="40" height="40" style="object-fit: cover;">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">${user.username}</h6>
                                            <small class="text-muted">${user.email}</small>
                                            <div class="mt-1">
                                                <small class="text-muted">积分: ${user.points || 0} | 等级: ${user.level || 1}</small>
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <small class="text-muted">${user.date_joined}</small>
                                            ${user.is_superuser ? '<span class="badge badge-admin ms-1">管理员</span>' : ''}
                                            ${!user.is_active ? '<span class="badge bg-danger ms-1">已禁用</span>' : ''}
                                        </div>
                                    </div>
                                    <div class="mt-2 action-buttons">
                                        ${!isCurrentUser ? `
                                            <button class="btn btn-sm ${user.is_active ? 'btn-warning' : 'btn-success'}" onclick="toggleUserStatus(${user.id})">
                                                <i class="fas ${user.is_active ? 'fa-ban' : 'fa-check'} me-1"></i>${user.is_active ? '禁用' : '启用'}
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">
                                                <i class="fas fa-trash me-1"></i>删除
                                            </button>
                                        ` : `
                                            <span class="text-muted small">（当前用户）</span>
                                        `}
                                    </div>
                                </div>
                            </div>
                        `;
                        usersContainer.innerHTML += userHTML;
                    });
                } else {
                    usersContainer.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-users fa-2x text-muted mb-3"></i>
                            <p class="text-muted">暂无用户数据</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading users:', error);
                showMessage('加载用户数据失败', 'error');
            });
    }

    // 切换用户状态
    function toggleUserStatus(userId) {
        const action = confirm('确定要切换这个用户的状态吗？');
        if (action) {
            fetch(`/customer/admin/toggle-user/${userId}/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCSRFToken(),
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message);
                    loadUsersData();
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error toggling user status:', error);
                showMessage('切换用户状态失败', 'error');
            });
        }
    }

    // 删除用户
    function deleteUser(userId) {
        if (confirm('确定要删除这个用户吗？此操作不可恢复！')) {
            fetch(`/customer/admin/delete-user/${userId}/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCSRFToken(),
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message);
                    loadUsersData();
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error deleting user:', error);
                showMessage('删除用户失败', 'error');
            });
        }
    }

    // ============================
    // 活动管理功能
    // ============================

    // 加载活动数据
    function loadEventsData() {
        fetch('/customer/admin/events-data/')
            .then(response => response.json())
            .then(data => {
                const eventsContainer = document.getElementById('events-list');
                eventsContainer.innerHTML = '';

                if (data.events && data.events.length > 0) {
                    data.events.forEach(event => {
                        const statusBadge = getStatusBadge(event.status, event.status_display);
                        const eventHTML = `
                            <div class="card recent-item">
                                <div class="card-body py-3">
                                    <h6 class="mb-2">${event.title}</h6>
                                    <div class="d-flex justify-content-between text-muted small mb-2">
                                        <span><i class="fas fa-user me-1"></i>${event.organizer}</span>
                                        <span><i class="fas fa-users me-1"></i>${event.current_participants}/${event.max_participants}</span>
                                        <span><i class="fas fa-calendar me-1"></i>${event.start_time}</span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            ${statusBadge}
                                            <small class="text-muted ms-2">${event.created_at}</small>
                                        </div>
                                        <div class="action-buttons">
                                            <button class="btn btn-info btn-sm" onclick="viewEventDetails(${event.id})">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            ${event.status === 'pending' ? `
                                            <button class="btn btn-success btn-sm" onclick="approveEvent(${event.id})">
                                                <i class="fas fa-check"></i>
                                            </button>
                                            ` : ''}
                                            <button class="btn btn-danger btn-sm" onclick="deleteEvent(${event.id})">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                        eventsContainer.innerHTML += eventHTML;
                    });
                } else {
                    eventsContainer.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-calendar-times fa-2x text-muted mb-3"></i>
                            <p class="text-muted">暂无活动数据</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading events:', error);
                showMessage('加载活动数据失败', 'error');
            });
    }

    // 状态徽章辅助函数
    function getStatusBadge(status, display) {
        const statusClasses = {
            'published': 'bg-success',
            'pending': 'badge-pending',
            'draft': 'bg-secondary',
            'rejected': 'bg-danger',
            'cancelled': 'bg-warning'
        };

        const badgeClass = statusClasses[status] || 'bg-warning';
        return `<span class="badge ${badgeClass}">${display}</span>`;
    }

    // 状态徽章类名辅助函数
    function getStatusBadgeClass(status) {
        const statusClasses = {
            'published': 'bg-success',
            'pending': 'badge-pending',
            'draft': 'bg-secondary',
            'rejected': 'bg-danger',
            'cancelled': 'bg-warning'
        };

        return statusClasses[status] || 'bg-warning';
    }

    // ============================
    // 活动审核功能
    // ============================

    // 加载待审核活动数据
    function loadPendingEventsData() {
        fetch('/customer/admin/pending-events-data/')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                console.log('待审核活动数据:', data);
                const pendingContainer = document.getElementById('pending-events-list');
                pendingContainer.innerHTML = '';

                if (data.pending_events && data.pending_events.length > 0) {
                    // 更新待审核计数
                    document.getElementById('pending-count').textContent = data.pending_events.length;

                    data.pending_events.forEach(event => {
                        const eventHTML = `
                            <div class="card recent-item" id="event-${event.id}">
                                <div class="card-body py-3">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-2">${event.title || '无标题'}</h6>
                                            <p class="text-muted small mb-2">${event.description || '无描述'}</p>
                                            <div class="d-flex flex-wrap text-muted small mb-2">
                                                <span class="me-3">
                                                    <i class="fas fa-user me-1"></i>${event.organizer || '未知组织者'}
                                                </span>
                                                <span class="me-3">
                                                    <i class="fas fa-calendar me-1"></i>${event.start_time || '未设置时间'}
                                                </span>
                                                <span>
                                                    <i class="fas fa-map-marker-alt me-1"></i>${event.location || '未设置地点'}
                                                </span>
                                            </div>
                                            <span class="badge badge-pending">待审核</span>
                                            <small class="text-muted ms-2">${event.created_at || ''}</small>
                                        </div>
                                        <div class="action-buttons ms-3">
                                            <button class="btn btn-info btn-sm mb-1" onclick="viewEventDetails(${event.id})" title="查看详情">
                                                <i class="fas fa-eye me-1"></i>详情
                                            </button>
                                            <button class="btn btn-success btn-sm mb-1" onclick="approveEvent(${event.id})" title="通过审核">
                                                <i class="fas fa-check me-1"></i>通过
                                            </button>
                                            <button class="btn btn-danger btn-sm mb-1" onclick="rejectEvent(${event.id})" title="拒绝审核">
                                                <i class="fas fa-times me-1"></i>拒绝
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                        pendingContainer.innerHTML += eventHTML;
                    });
                } else {
                    pendingContainer.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-check-circle fa-2x text-muted mb-3"></i>
                            <p class="text-muted">暂无待审核活动</p>
                        </div>
                    `;
                    // 更新待审核计数为0
                    document.getElementById('pending-count').textContent = '0';
                }
            })
            .catch(error => {
                console.error('Error loading pending events:', error);
                showMessage('加载待审核活动数据失败: ' + error.message, 'error');
                const pendingContainer = document.getElementById('pending-events-list');
                pendingContainer.innerHTML = `
                    <div class="text-center py-4">
                        <i class="fas fa-exclamation-triangle fa-2x text-warning mb-3"></i>
                        <p class="text-warning">加载数据失败，请刷新页面重试</p>
                        <button class="btn btn-primary btn-sm" onclick="loadPendingEventsData()">重试</button>
                    </div>
                `;
            });
    }

    // 查看活动详情
    function viewEventDetails(eventId) {
        console.log('尝试获取活动详情:', eventId);

        // 显示加载状态
        const modalContent = document.getElementById('eventDetailsContent');
        modalContent.innerHTML = '<div class="text-center py-4"><div class="spinner-border" role="status"></div><p class="mt-2">加载中...</p></div>';

        // 先显示模态框
        const modal = new bootstrap.Modal(document.getElementById('eventDetailsModal'));
        modal.show();

        fetch(`/customer/admin/view-event/${eventId}/`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('详情响应数据:', data);
                if (data.success) {
                    const event = data.event;

                    // 构建详情HTML - 使用实际存在的字段
                    modalContent.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <div class="event-detail-item">
                                    <span class="event-detail-label">活动标题:</span>
                                    <span>${event.title || '无标题'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">组织者:</span>
                                    <span>${event.organizer || '未知'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">分类:</span>
                                    <span>${event.category || '未分类'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">开始时间:</span>
                                    <span>${event.start_time || '未设置'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">结束时间:</span>
                                    <span>${event.end_time || '未设置'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">报名截止:</span>
                                    <span>${event.registration_deadline || '未设置'}</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="event-detail-item">
                                    <span class="event-detail-label">地点:</span>
                                    <span>${event.location || '未设置'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">参与人数:</span>
                                    <span>${event.current_participants || 0}/${event.max_participants || 0}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">状态:</span>
                                    <span class="badge ${getStatusBadgeClass(event.status)}">${event.status_display || '未知'}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">费用:</span>
                                    <span>${event.is_free ? '免费' : `¥${event.fee || 0}`}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">浏览数:</span>
                                    <span>${event.views_count || 0}</span>
                                </div>
                                <div class="event-detail-item">
                                    <span class="event-detail-label">点赞数:</span>
                                    <span>${event.likes_count || 0}</span>
                                </div>
                            </div>
                        </div>
                        <div class="event-detail-item">
                            <span class="event-detail-label">活动描述:</span>
                            <p class="mt-2 p-3 bg-light rounded">${event.description || '无描述'}</p>
                        </div>
                        <div class="event-detail-item">
                            <span class="event-detail-label">地点详情:</span>
                            <p class="mt-2 p-3 bg-light rounded">${event.location_details || '无详细地点信息'}</p>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="event-detail-item">
                                    <span class="event-detail-label">创建时间:</span>
                                    <span>${event.created_at || '未知'}</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="event-detail-item">
                                    <span class="event-detail-label">更新时间:</span>
                                    <span>${event.updated_at || '未知'}</span>
                                </div>
                            </div>
                        </div>
                    `;

                } else {
                    modalContent.innerHTML = `
                        <div class="text-center py-4">
                            <i class="fas fa-exclamation-triangle fa-2x text-warning mb-3"></i>
                            <p class="text-warning">${data.message || '获取详情失败'}</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading event details:', error);
                modalContent.innerHTML = `
                    <div class="text-center py-4">
                        <i class="fas fa-exclamation-triangle fa-2x text-danger mb-3"></i>
                        <p class="text-danger">获取活动详情失败: ${error.message}</p>
                        <button class="btn btn-primary btn-sm" onclick="viewEventDetails(${eventId})">重试</button>
                    </div>
                `;
            });
    }

        // 批准活动
     function approveEvent(eventId) {
    if (confirm('确定要批准这个活动吗？批准后活动将发布并自动发放积分给创建者。')) {
        // 显示处理中的消息
        showMessage('正在批准活动并发放积分...', 'success');

        fetch(`/customer/admin/approve-event/${eventId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(),
                'Content-Type': 'application/json',
            },
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                // 批准成功后，发放积分
                return grantPointsForPublishedEvent(eventId).then(pointsResult => {
                    // 整合两个操作的结果消息
                    let finalMessage = data.message;
                    if (pointsResult.success) {
                        finalMessage += `，${pointsResult.message}`;
                    } else {
                        finalMessage += `，但积分发放失败: ${pointsResult.message}`;
                    }

                    showMessage(finalMessage, pointsResult.success ? 'success' : 'warning');

                    // 重新加载数据
                    if (currentView === 'approval') {
                        loadPendingEventsData();
                    } else if (currentView === 'events') {
                        loadEventsData();
                    }
                });
            } else {
                showMessage(data.message, 'error');
                throw new Error(data.message);
            }
        })
        .catch(error => {
            console.error('批准活动失败:', error);
            showMessage('批准活动失败: ' + error.message, 'error');
        });
    }
}

     // 为已发布活动发放积分
     function grantPointsForPublishedEvent(eventId) {
    console.log(`🔍 [前端] 开始发放积分，活动ID: ${eventId}`);

    return fetch(`/customer/admin/grant-points/${eventId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCSRFToken(),
            'Content-Type': 'application/json',
        },
    })
    .then(response => {
        console.log(`🔍 [前端] 积分发放响应状态: ${response.status}`);
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log(`🔍 [前端] 积分发放响应数据:`, data);
        return {
            success: data.success || false,
            message: data.message || '积分发放完成',
            points: data.points || 0
        };
    })
    .catch(error => {
        console.error('❌ [前端] 积分发放失败:', error);
        return {
            success: false,
            message: `请求失败: ${error.message}`
        };
    });
}

    // 拒绝活动
    function rejectEvent(eventId) {
        if (confirm('确定要拒绝这个活动吗？拒绝后活动将不会发布。')) {
            showMessage('正在处理...', 'success');

            fetch(`/customer/admin/reject-event/${eventId}/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCSRFToken(),
                    'Content-Type': 'application/json',
                },
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showMessage(data.message || '活动已成功拒绝');
                    // 从DOM中移除被拒绝的活动
                    const eventElement = document.getElementById(`event-${eventId}`);
                    if (eventElement) {
                        eventElement.remove();
                    }
                    // 重新加载数据
                    loadPendingEventsData();
                } else {
                    showMessage(data.message || '拒绝活动失败', 'error');
                }
            })
            .catch(error => {
                console.error('Error rejecting event:', error);
                showMessage('拒绝活动失败: ' + error.message, 'error');
            });
        }
    }

    // 删除活动
    function deleteEvent(eventId) {
        if (confirm('确定要删除这个活动吗？此操作不可恢复！')) {
            fetch(`/customer/admin/delete-event/${eventId}/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCSRFToken(),
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message);
                    // 重新加载数据
                    if (currentView === 'events') {
                        loadEventsData();
                    } else if (currentView === 'approval') {
                        loadPendingEventsData();
                    }
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error deleting event:', error);
                showMessage('删除活动失败', 'error');
            });
        }
    }

    // ============================
    // 积分管理功能
    // ============================

    // 积分管理相关变量
    let currentPointsPage = 1;
    let pointsLimit = 10;

    // 显示积分调整卡片
    function showAdjustPointsCard() {
        document.getElementById('adjustPointsCard').style.display = 'block';
    }

    // 隐藏积分调整卡片
    function hideAdjustPointsCard() {
        document.getElementById('adjustPointsCard').style.display = 'none';
        // 清空表单
        document.getElementById('adjust-user-ids').value = '';
        document.getElementById('adjust-points').value = '';
        document.getElementById('adjust-remark').value = '管理员调整';
    }

    // 提交积分调整
    function submitAdjustPoints() {
        const userIds = document.getElementById('adjust-user-ids').value.trim();
        const points = parseInt(document.getElementById('adjust-points').value);
        const remark = document.getElementById('adjust-remark').value || '管理员调整';

        if (!userIds) {
            showMessage('请输入用户ID', 'error');
            return;
        }

        if (isNaN(points)) {
            showMessage('请输入有效的积分数量', 'error');
            return;
        }

        const userIdsArray = userIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));

        if (userIdsArray.length === 0) {
            showMessage('请输入有效的用户ID', 'error');
            return;
        }

        if (userIdsArray.length === 1) {
            // 单个用户调整
            adjustSinglePoints(userIdsArray[0], points, remark);
        } else {
            // 批量调整
            batchAdjustPoints(userIdsArray, points, remark);
        }

        // 隐藏卡片
        hideAdjustPointsCard();
    }

    // 加载积分管理数据
    function loadPointsData() {
        const username = document.getElementById('search-username').value;
        const phone = document.getElementById('search-phone').value;
        const transactionType = document.getElementById('search-transaction-type').value;
        const sourceType = document.getElementById('search-source-type').value;
        const startTime = document.getElementById('search-start-time').value;
        const endTime = document.getElementById('search-end-time').value;

        let url = `/customer/admin/points/list/?page=${currentPointsPage}&limit=${pointsLimit}`;

        if (username) url += `&username=${encodeURIComponent(username)}`;
        if (phone) url += `&phone=${encodeURIComponent(phone)}`;
        if (transactionType) url += `&transaction_type=${transactionType}`;
        if (sourceType) url += `&source_type=${sourceType}`;
        if (startTime) url += `&start_time=${startTime}`;
        if (endTime) url += `&end_time=${endTime}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderPointsList(data.data);
                    updatePointsPagination(data);
                    loadPointsStatistics();
                } else {
                    showMessage('加载积分数据失败', 'error');
                }
            })
            .catch(error => {
                console.error('Error loading points data:', error);
                showMessage('加载积分数据失败', 'error');
            });
    }

    // 渲染积分列表
    function renderPointsList(pointsData) {
        const container = document.getElementById('points-list');
        container.innerHTML = '';

        if (pointsData && pointsData.length > 0) {
            pointsData.forEach(record => {
                const pointsClass = record.transaction_type === 'earn' ? 'text-success' :
                                  record.transaction_type === 'spend' ? 'text-danger' : 'text-warning';
                const pointsSign = record.transaction_type === 'earn' ? '+' :
                                 record.transaction_type === 'spend' ? '-' : '';

                const recordHTML = `
                    <div class="card recent-item">
                        <div class="card-body py-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">${record.username} (${record.phone})</h6>
                                    <div class="d-flex text-muted small mb-1">
                                        <span class="me-3">
                                            <i class="fas fa-exchange-alt me-1"></i>${record.transaction_type_display}
                                        </span>
                                        <span class="me-3">
                                            <i class="fas fa-tag me-1"></i>${record.source_type_display}
                                        </span>
                                        <span>
                                            <i class="fas fa-clock me-1"></i>${record.created_at}
                                        </span>
                                    </div>
                                    <p class="text-muted small mb-0">${record.description}</p>
                                    ${record.related_info ? `<small class="text-info">${record.related_info}</small>` : ''}
                                </div>
                                <div class="text-end">
                                    <div class="${pointsClass} fw-bold fs-5">
                                        ${pointsSign}${record.points}
                                    </div>
                                    <button class="btn btn-sm btn-outline-info mt-1" onclick="viewUserPointsDetail('${record.username}')">
                                        <i class="fas fa-user me-1"></i>详情
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                container.innerHTML += recordHTML;
            });
        } else {
            container.innerHTML = `
                <div class="text-center py-4">
                    <i class="fas fa-coins fa-2x text-muted mb-3"></i>
                    <p class="text-muted">暂无积分记录</p>
                </div>
            `;
        }
    }

    // 更新积分分页
    function updatePointsPagination(data) {
        const infoElement = document.getElementById('points-pagination-info');
        const paginationElement = document.getElementById('points-pagination');

        const start = (data.page - 1) * data.limit + 1;
        const end = Math.min(data.page * data.limit, data.total);

        infoElement.textContent = `显示 ${start}-${end} 条记录，共 ${data.total} 条`;

        // 生成分页按钮
        let paginationHTML = '';
        const totalPages = data.total_pages;

        if (totalPages > 1) {
            // 上一页
            if (data.page > 1) {
                paginationHTML += `<li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="changePointsPage(${data.page - 1})">上一页</a>
                </li>`;
            }

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === data.page) {
                    paginationHTML += `<li class="page-item active">
                        <span class="page-link">${i}</span>
                    </li>`;
                } else {
                    paginationHTML += `<li class="page-item">
                        <a class="page-link" href="javascript:void(0)" onclick="changePointsPage(${i})">${i}</a>
                    </li>`;
                }
            }

            // 下一页
            if (data.page < totalPages) {
                paginationHTML += `<li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="changePointsPage(${data.page + 1})">下一页</a>
                </li>`;
            }
        }

        paginationElement.innerHTML = paginationHTML;
    }

    // 切换积分页面
    function changePointsPage(page) {
        currentPointsPage = page;
        loadPointsData();
    }

    // 加载积分统计
    function loadPointsStatistics() {
        const startTime = document.getElementById('search-start-time').value;
        const endTime = document.getElementById('search-end-time').value;

        let url = '/customer/admin/points/statistics/';
        if (startTime || endTime) {
            url += '?';
            if (startTime) url += `start_time=${startTime}`;
            if (endTime) url += `${startTime ? '&' : ''}end_time=${endTime}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const stats = data.statistics;
                    document.getElementById('stats-total-issued').textContent = stats.total_points_issued;
                    document.getElementById('stats-total-used').textContent = stats.total_points_used;
                    document.getElementById('stats-total-transactions').textContent = stats.total_transactions;
                    document.getElementById('stats-unique-users').textContent = stats.unique_users;
                }
            })
            .catch(error => {
                console.error('Error loading points statistics:', error);
            });
    }

    // 调整单个用户积分
    function adjustSinglePoints(userId, points, remark) {
        fetch('/customer/admin/points/adjust/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(),
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                user_id: userId,
                points: points,
                remark: remark
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage(data.message);
                loadPointsData();
                loadPointsStatistics();
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error adjusting points:', error);
            showMessage('调整积分失败', 'error');
        });
    }

    // 批量调整积分
    function batchAdjustPoints(userIds, points, remark) {
        fetch('/customer/admin/points/batch-adjust/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(),
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                user_ids: userIds,
                points: points,
                remark: remark
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage(`${data.message}, 成功: ${data.success_count}, 失败: ${data.error_count}`);
                if (data.error_messages && data.error_messages.length > 0) {
                    data.error_messages.forEach(msg => console.warn(msg));
                }
                loadPointsData();
                loadPointsStatistics();
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error batch adjusting points:', error);
            showMessage('批量调整积分失败', 'error');
        });
    }

    // 显示积分规则
    function showPointsRules() {
        fetch('/customer/admin/points/rules/')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const modalContent = document.getElementById('points-rules-content');
                    let rulesHTML = '<div class="table-responsive"><table class="table table-striped"><thead><tr><th>规则类型</th><th>积分值</th><th>每日上限</th><th>状态</th><th>操作</th></tr></thead><tbody>';

                    data.rules.forEach(rule => {
                        rulesHTML += `
                            <tr>
                                <td>${rule.rule_type_display}</td>
                                <td>
                                    <input type="number" class="form-control form-control-sm" id="points-${rule.id}" value="${rule.points}" min="0">
                                </td>
                                <td>
                                    <input type="number" class="form-control form-control-sm" id="limit-${rule.id}" value="${rule.daily_limit}" min="0">
                                </td>
                                <td>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="active-${rule.id}" ${rule.is_active ? 'checked' : ''}>
                                        <label class="form-check-label" for="active-${rule.id}">${rule.is_active ? '启用' : '禁用'}</label>
                                    </div>
                                </td>
                                <td>
                                    <button class="btn btn-primary btn-sm" onclick="updatePointsRule(${rule.id})">保存</button>
                                </td>
                            </tr>
                        `;
                    });

                    rulesHTML += '</tbody></table></div>';
                    modalContent.innerHTML = rulesHTML;

                    const modal = new bootstrap.Modal(document.getElementById('pointsRulesModal'));
                    modal.show();
                } else {
                    showMessage('加载积分规则失败', 'error');
                }
            })
            .catch(error => {
                console.error('Error loading points rules:', error);
                showMessage('加载积分规则失败', 'error');
            });
    }

    // 更新积分规则
    function updatePointsRule(ruleId) {
        const points = parseInt(document.getElementById(`points-${ruleId}`).value);
        const dailyLimit = parseInt(document.getElementById(`limit-${ruleId}`).value);
        const isActive = document.getElementById(`active-${ruleId}`).checked;

        fetch(`/customer/admin/points/rules/update/${ruleId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(),
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                points: points,
                daily_limit: dailyLimit,
                is_active: isActive
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage('积分规则更新成功');
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error updating points rule:', error);
            showMessage('更新积分规则失败', 'error');
        });
    }

    // 导出积分数据
    function exportPointsData() {
        const username = document.getElementById('search-username').value;
        const phone = document.getElementById('search-phone').value;
        const sourceType = document.getElementById('search-source-type').value;
        const transactionType = document.getElementById('search-transaction-type').value;
        const startTime = document.getElementById('search-start-time').value;
        const endTime = document.getElementById('search-end-time').value;

        let url = '/customer/admin/points/export/';
        let params = [];

        if (username) params.push(`username=${encodeURIComponent(username)}`);
        if (phone) params.push(`phone=${encodeURIComponent(phone)}`);
        if (sourceType) params.push(`source_type=${sourceType}`);
        if (transactionType) params.push(`transaction_type=${transactionType}`);
        if (startTime) params.push(`start_time=${startTime}`);
        if (endTime) params.push(`end_time=${endTime}`);

        if (params.length > 0) {
            url += '?' + params.join('&');
        }

        // 创建隐藏的链接进行下载
        const link = document.createElement('a');
        link.href = url;
        link.download = 'points_data.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        showMessage('导出任务已开始，请稍候...');
    }

    // 查看用户积分详情
    function viewUserPointsDetail(username) {
        // 这里可以实现查看用户积分详情的功能
        showMessage(`查看用户 ${username} 的积分详情功能开发中...`, 'info');
    }

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 默认显示仪表板并加载数据
        showView('dashboard');
        loadDashboardData();
    });
    // ============================
// 数据统计功能
// ============================

// 加载统计数据
function loadStatisticsData() {
    fetch('/customer/admin/data-statistics/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const stats = data.statistics;

                // 更新概览数据
                document.getElementById('stats-total-users').textContent = stats.users.total;
                document.getElementById('stats-total-events').textContent = stats.events.total;
                document.getElementById('stats-active-users').textContent = stats.users.active_30d;
                document.getElementById('stats-total-points').textContent = stats.points.total;

                // 渲染图表
                renderRegistrationChart(stats.trends.registration);
                renderEventsChart(stats.trends.events);
                renderLevelChart(stats.distributions.levels);
                renderCategoryChart(stats.distributions.categories);
            } else {
                showMessage('加载统计数据失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error loading statistics:', error);
            showMessage('加载统计数据失败', 'error');
        });
}

// 刷新统计数据
function refreshStatistics() {
    showMessage('正在刷新数据...', 'success');
    loadStatisticsData();
}

// 渲染注册趋势图表
function renderRegistrationChart(data) {
    const container = document.getElementById('registration-chart');

    if (data && data.length > 0) {
        // 这里可以使用 Chart.js 或 ECharts 来渲染图表
        // 暂时用简单的HTML表格显示
        let html = '<div class="table-responsive"><table class="table table-sm table-striped"><thead><tr><th>日期</th><th>注册人数</th></tr></thead><tbody>';

        data.forEach(item => {
            html += `<tr><td>${item.date}</td><td>${item.count}</td></tr>`;
        });

        html += '</tbody></table></div>';
        container.innerHTML = html;
    } else {
        container.innerHTML = '<div class="text-center py-4 text-muted">暂无数据</div>';
    }
}

// 渲染活动趋势图表
function renderEventsChart(data) {
    const container = document.getElementById('events-chart');

    if (data && data.length > 0) {
        let html = '<div class="table-responsive"><table class="table table-sm table-striped"><thead><tr><th>日期</th><th>活动数量</th></tr></thead><tbody>';

        data.forEach(item => {
            html += `<tr><td>${item.date}</td><td>${item.count}</td></tr>`;
        });

        html += '</tbody></table></div>';
        container.innerHTML = html;
    } else {
        container.innerHTML = '<div class="text-center py-4 text-muted">暂无数据</div>';
    }
}

// 渲染等级分布图表
function renderLevelChart(data) {
    const container = document.getElementById('level-chart');

    if (data && data.length > 0) {
        let html = '<div class="table-responsive"><table class="table table-sm table-striped"><thead><tr><th>等级</th><th>用户数量</th></tr></thead><tbody>';

        data.forEach(item => {
            html += `<tr><td>${item.level}</td><td>${item.count}</td></tr>`;
        });

        html += '</tbody></table></div>';
        container.innerHTML = html;
    } else {
        container.innerHTML = '<div class="text-center py-4 text-muted">暂无数据</div>';
    }
}

// 渲染分类图表
function renderCategoryChart(data) {
    const container = document.getElementById('category-chart');

    if (data && data.length > 0) {
        let html = '<div class="table-responsive"><table class="table table-sm table-striped"><thead><tr><th>分类</th><th>活动数</th><th>平均参与</th></tr></thead><tbody>';

        data.forEach(item => {
            html += `<tr><td>${item.name}</td><td>${item.count}</td><td>${item.avg_participants}</td></tr>`;
        });

        html += '</tbody></table></div>';
        container.innerHTML = html;
    } else {
        container.innerHTML = '<div class="text-center py-4 text-muted">暂无数据</div>';
    }
}

// ============================
// 系统设置功能
// ============================

// 加载系统设置
function loadSystemSettings() {
    fetch('/customer/admin/system-settings/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const settings = data.settings;

                // 填充表单
                document.getElementById('setting-site-name').value = settings.site_name;
                document.getElementById('setting-admin-email').value = settings.admin_email;
                document.getElementById('setting-site-description').value = settings.site_description;
                document.getElementById('setting-auto-approve').checked = settings.auto_approve_events;
                document.getElementById('setting-points-enabled').checked = settings.points_enabled;
                document.getElementById('setting-registration-open').checked = settings.registration_open;
                document.getElementById('setting-maintenance-mode').checked = settings.maintenance_mode;

                // 加载系统信息
                updateSystemInfo();
            } else {
                showMessage('加载系统设置失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error loading settings:', error);
            showMessage('加载系统设置失败', 'error');
        });
}

// 保存系统设置
function saveSystemSettings() {
    const settings = {
        site_name: document.getElementById('setting-site-name').value,
        admin_email: document.getElementById('setting-admin-email').value,
        site_description: document.getElementById('setting-site-description').value,
        auto_approve_events: document.getElementById('setting-auto-approve').checked,
        points_enabled: document.getElementById('setting-points-enabled').checked,
        registration_open: document.getElementById('setting-registration-open').checked,
        maintenance_mode: document.getElementById('setting-maintenance-mode').checked
    };

    fetch('/customer/admin/update-settings/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCSRFToken(),
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(settings)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message);
        } else {
            showMessage(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error saving settings:', error);
        showMessage('保存设置失败', 'error');
    });
}

// 清除系统缓存
function clearSystemCache() {
    if (confirm('确定要清除系统缓存吗？')) {
        fetch('/customer/admin/clear-cache/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(),
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage(data.message);
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error clearing cache:', error);
            showMessage('清除缓存失败', 'error');
        });
    }
}

// 创建系统备份
function createSystemBackup() {
    if (confirm('确定要创建系统备份吗？')) {
        fetch('/customer/admin/system-backup/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCSRFToken(),
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage(data.message);
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error creating backup:', error);
            showMessage('创建备份失败', 'error');
        });
    }
}

// 更新系统信息
function updateSystemInfo() {
    // 这里可以添加获取真实系统信息的逻辑
    document.getElementById('info-django-version').textContent = '4.2.0';
    document.getElementById('info-python-version').textContent = '3.9+';
    document.getElementById('info-database').textContent = 'SQLite/MySQL';
    document.getElementById('info-server-time').textContent = new Date().toLocaleString();
    document.getElementById('info-uptime').textContent = '24小时';
}

// 系统健康检查
function checkSystemHealth() {
    showMessage('系统健康检查功能开发中...', 'info');
}
    </script>
</body>
</html>